import { useEffect, useRef, useState } from 'react';

/**
 * useCountDown - 一个通用的倒计时 Hook
 * @param duration 倒计时时间（秒）
 * @param onFinish 倒计时结束时的回调函数
 */
export const useCountDown = (duration: number) => {
  const [timeLeft, setTimeLeft] = useState(duration); // 剩余时间
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const isFinishedRef = useRef(false); // 用于确保 onFinish 只触发一次

  useEffect(() => {
    // 启动倒计时
    intervalRef.current = setInterval(() => {
      setTimeLeft((prev) => {
        if (prev <= 1) {
          if (intervalRef.current) {
            clearInterval(intervalRef.current);
          }
          if (!isFinishedRef.current) {
            isFinishedRef.current = true; // 标记为已完成，避免重复触发
          }
          return 0;
        }
        return prev - 1; // 每秒减少1秒
      });
    }, 1000);

    // 在组件卸载时清理定时器
    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, []);

  // 重置倒计时的函数
  const resetCountdown = () => {
    setTimeLeft(duration);
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
    }
    intervalRef.current = setInterval(() => {
      setTimeLeft((prev) => {
        if (prev <= 1) {
          if (intervalRef.current !== null) {
            clearInterval(intervalRef.current);
          }
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };

  /** 停止倒计时 */
  const stopCountdown = () => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
    }
  };
  /** 继续倒计时 */
  const continueCountdown = () => {
    intervalRef.current = setInterval(() => {
      setTimeLeft((prev) => {
        if (prev <= 1) {
          if (intervalRef.current) {
            clearInterval(intervalRef.current);
          }
          if (!isFinishedRef.current) {
            isFinishedRef.current = true; // 标记为已完成，避免重复触发
          }
          return 0;
        }
        return prev - 1; // 每秒减少1秒
      });
    }, 1000);
  };

  return {
    timeLeft,
    resetCountdown,
    stopCountdown,
    continueCountdown,
  };
};
